<template>
  <div class="add-edit-collect-form">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :labelCol="{ style: { width: '84px', marginRight: '21px' } }"
      labelAlign="right"
      :colon="false"
      @finish="handleFinish"
    >
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="基础配置">
          <BasicConfig ref="basicConfig" :formData="formData" :formRef="formRef" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="其他信息" force-render>
          <OtherInfo :formData="formData" />
        </a-tab-pane>
      </a-tabs>

      <a-divider />

      <a-form-item style="margin-right: 0">
        <a-button type="primary" html-type="submit" :loading="confirmLoading">保存采集资源</a-button>
        <a-button style="margin-left: 10px" @click="handleBack">返回</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup name="AddEditCollectForm">
import BasicConfig from './components/BasicConfig.vue'
import OtherInfo from './components/OtherInfo.vue'
import mitt from '@/utils/mitt'
import { message } from 'ant-design-vue'
import type { CollectFormType, CollectFormBindType } from '../public-type'
import type { Rule } from 'ant-design-vue/es/form'
import { useRouter, useRoute } from 'vue-router'
import { computed, onUnmounted, reactive, ref, watch } from 'vue'

import apis from '@/apis'
import { getSiteClassification } from '@/stores/modules/collect-manage/select-data-source'

// tabs
const activeKey = ref<string>('1')

// id
const route = useRoute()
const { id } = route.query

// api
const { addCollect, getCollectInfo, updateCollect } = apis.collectManage

// basicConfig
const basicConfig = ref()

// form-data
const formRef = ref()

let formData = ref<CollectFormType>({
  name: '', // 资源名称
  resource_type: undefined, // 资源类型
  content_type: undefined, // 内容类型
  collect_addr: '', // 接口地址
  seed_key: '', // 种源密钥
  video_resource_type: [], // 文件类型
  other_param: '', // 其他参数
  interface_type: 1, // 接口类型
  data_handing: 1, // 数据处理
  site_id: undefined, // 采集到站点
  status: 1, // 状态
  bind: [], // 绑定分类
  res_description: '' // 资源描述
})
// let formData = reactive<CollectFormType>({
//   name: '资源A', // 资源名称
//   resource_type: 1, // 资源类型
//   content_type: 1, // 内容类型
//   collect_addr: 'http://srv-seed-mgr-test-8000.test.com', // 接口地址
//   seed_key: 'DqnULmrHfuGXCRKbyUgwJUedWNacDEIQ', // 种源密钥
//   video_resource_type: [1], // 文件类型
//   other_param: '', // 其他参数
//   interface_type: 1, // 接口类型
//   data_handing: 1, // 数据处理
//   site_id: undefined, // 采集到站点
//   status: 1, // 状态
//   bind: [],
//   res_description: '资源描述' // 资源描述
// })
const addressReg = /(http|https):\/\/([\w.]+\/?)\S*/
const checkAddress = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.reject('请输入接口地址')
  } else if (!addressReg.test(value)) {
    return Promise.reject('请输入合法的接口地址')
  } else {
    return Promise.resolve()
  }
}
// form-rule
const rules: Record<string, Rule[]> = {
  name: [{ required: true, trigger: 'blur' }],
  resource_type: [{ required: true, trigger: 'change' }],
  content_type: [{ required: true, trigger: 'change' }],
  collect_addr: [{ required: true, validator: checkAddress, trigger: 'blur' }],
  video_resource_type: [{ required: true, trigger: 'change', message: '请选择文件类型' }],
  site_id: [{ required: true, trigger: 'change' }]
}

// 编辑反显处理站点分类 select 数据
const formatterSelectValue = (data: CollectFormBindType[]): CollectFormBindType[] => {
  return data.map((m: any) => {
    console.log('m: ', m)
    return {
      ...m,
      selectIds: getIds(m)
    }
  })
}
const getIds = (item: any) => {
  // m.site_category_id && m.site_sub_category_id ? [m.site_category_id, m.site_sub_category_id] : undefined
  if (item.site_category_id && item.site_sub_category_id) {
    return [item.site_category_id, item.site_sub_category_id]
  } else if (item.site_category_id && !item.site_sub_category_id) {
    return [item.site_category_id]
  } else if (!item.site_sub_category_id || (item.site_category_id && !item.site_sub_category_id)) {
    return undefined
  } else {
    return []
  }
}
// 编辑反显
const getEditFormData = () => {
  getCollectInfo({ collect_id: id as string }).then((res: any) => {
    res.collect.bind.forEach((item: any) => {
      Object.keys(item).forEach((sub: any) => {
        console.log('item[sub]: ', sub, item[sub])
        console.log(item.site_category, 'item.site_category')
        if (item[sub] == '0' || !item[sub]) {
          item[sub] = undefined
        }
      })
    })
    console.log('res.collect.bind: ', res.collect.bind)
    formData.value = res.collect
    if (!formData.value.site_id || formData.value.site_id === '0') formData.value.site_id = undefined

    // 设置绑定分类 回显数据
    if (!res.collect.bind.length) return
    formData.value.bind = formatterSelectValue(formData.value.bind)

    basicConfig.value.editSetSiteClassificationTableData(formData.value.bind)

    // 设置站点分类 select 数据
    const content_type = formData.value.content_type as number
    const site_id = formData.value.site_id as string
    getSiteClassification(content_type, { site_id })

    console.log(formData.value)
  })
}
id && getEditFormData()

// form-handle
const confirmLoading = ref<boolean>(false)

const router = useRouter()
const handleBack = () => {
  formRef.value.resetFields()
  router.back()
}

// 提交 btn，message 文案及状态
const getMessageText = () => {
  return id ? '编辑' : '添加'
}

// 获取 submitRequestApi
const getSubmitRequestApi = (): Function => {
  return id ? updateCollect : addCollect
}

// 组装提交数据
const getSubmitData = () => {
  formData.value.bind = basicConfig.value.getFilterSiteClassificationTableData()
  return { ...formData.value }
}

// 新增成功如果 activeKey = 2 则恢复 1
const setAddSuccessTabsActiveKey = () => {
  if (activeKey.value === '2') activeKey.value = '1'
}

const submitHandle = () => {
  const requestApi = getSubmitRequestApi()
  const submitData = getSubmitData()

  console.log(submitData, 'submitData=-=-=-=-=-=-=-=-=-=')

  confirmLoading.value = true
  requestApi(submitData)
    .then((res: any) => {
      confirmLoading.value = false
      formRef.value.resetFields()
      basicConfig.value.resetSiteClassificationTableData()
      message.success(`${getMessageText()}成功`)
      setAddSuccessTabsActiveKey()
      router.back()
    })
    .catch(() => {
      confirmLoading.value = false
    })
}

const handleFinish = (values: CollectFormType) => {
  console.log(getSubmitData(), 'getSubmitData=-=-=-=-=-=-=-=-=-=')
  // 判断 站点是否完全绑定
  const status = basicConfig.value.validateSiteClassificationTableData()
  if (status) {
    submitHandle()
  } else {
    basicConfig.value.siteClassificationMessageModel()
  }
}

// 采集 model 确认
mitt.on('modal-confirm', (): void => {
  submitHandle()
})

onUnmounted(() => {
  mitt.off('modal-confirm')
})
</script>

<style lang="less" scoped>
.add-edit-collect-form {
  // width: 554px;

  .ant-tabs {
    :deep(.ant-tabs-nav) {
      // background-color: red;
      margin-bottom: 24px;
    }
  }
}
</style>
